var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  default: () => src_default
});
module.exports = __toCommonJS(src_exports);
var import_debug = __toESM(require("debug"));
var import_withTmpPath = require("./utils/withTmpPath");
var debug = (0, import_debug.default)("@szzj/umi-plugin-drs-adapter");
var src_default = (api) => {
  api.describe({
    key: "drsAdapter",
    config: {
      default: {
        /** 当响应返回 success = false 时，是否展示错误提示，默认展示 */
        showErrorWhenSuccessEqualFalse: true,
        enableSubAppGetUserInfo: true,
        forceIsSubApp: {
          enable: false,
          isSubApp: false
        }
      },
      schema(Joi) {
        return Joi.alternatives().try(
          Joi.object({
            showErrorWhenSuccessEqualFalse: Joi.boolean(),
            enableSubAppGetUserInfo: Joi.boolean(),
            forceIsSubApp: Joi.object({
              enable: Joi.boolean(),
              isSubApp: Joi.boolean().required()
            })
          }),
          Joi.boolean().invalid(true)
        );
      }
    },
    enableBy: api.EnableBy.register
  });
  api.onGenerateFiles(() => {
    var _a, _b, _c;
    const {
      showErrorWhenSuccessEqualFalse = true,
      enableSubAppGetUserInfo = true,
      forceIsSubApp = { enable: false, isSubApp: false }
    } = api.userConfig.drsAdapter || {};
    const isSubapp = (forceIsSubApp == null ? void 0 : forceIsSubApp.enable) ? forceIsSubApp.isSubApp : process.env.UMI_ENV === "subapp" || !!((_a = api.userConfig.qiankun) == null ? void 0 : _a.slave) && ((_c = (_b = api.userConfig.qiankun) == null ? void 0 : _b.slave) == null ? void 0 : _c.enable) !== false;
    debug("isSubapp is", isSubapp);
    api.writeTmpFile({
      path: "index.tsx",
      content: isSubapp ? `import { useModel } from 'umi';
import { PermissionWrapper, useDrsConnect, getDrsToken, setDrsToken } from '@szzj/drs-share';
import type { IDrsState } from 'umi';

export { PermissionWrapper, useDrsConnect, getDrsToken, setDrsToken };

/**
 * 是否子应用
 */
export const IS_SUBAPP = true;

/**
 * 统一共享数据接口
 */
export const useDrsState = () => {
  ${enableSubAppGetUserInfo ? `const { appCode, globalHistory } = (useModel('@@qiankunStateFromMaster') || {}) as IDrsState;
  const rest = (useModel('@@drsModelForSlave') || {});
  return { appCode, globalHistory, ...rest };` : `const drsState = (useModel('@@qiankunStateFromMaster') || {}) as IDrsState;
      return drsState;`}

};` : `import { useModel } from 'umi';
import { PermissionWrapper, useDrsConnect, getDrsToken, setDrsToken } from '@szzj/drs-share';
import type { IDrsState } from 'umi';

export { PermissionWrapper, useDrsConnect, getDrsToken, setDrsToken };

/**
 * 是否子应用
 */
export const IS_SUBAPP = false;

/**
 * 统一共享数据接口
 */
export const useDrsState = () => {
  const drsState = (useModel('@@drsModel') || {}) as IDrsState;

  return drsState;
};`
    });
    api.writeTmpFile({
      path: "runtime.ts",
      content: `import { request } from 'umi';
import { message } from 'antd';

import type { Context } from 'umi-request';

const HttpStatusMap: Record<number, string> = {
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误。',
  501: '服务器不具备完成请求的功能。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或停机维护。',
  504: '网关超时。',
  505: 'HTTP 版本不受支持。',
};

request.extendOptions({
  timeout: 8000,
  errorHandler: (error: ResponseError) => {
    const { options } = error?.request ?? {};
  
    if (error?.response) {
      const { status } = error?.response;
  
      if (String(status).indexOf('20') !== 0) {
        const isLocal = process.env.NODE_ENV === 'development';
        switch (status) {
          case 401:
          case 402:
          case 403:
            if (!isLocal) window.dispatchEvent(new Event('403'));
            break;
          case 404:
            if (!isLocal) window.dispatchEvent(new Event('404'));
            break;
          default:
            const errorMessage = HttpStatusMap[error?.response.status] ?? error?.message;
            message.error(errorMessage);
        }
      }
    } else {
      message.error(error?.message);
    }
  
    throw error;
  }
});

/**
 * token 失效，触发 tokenExpire 事件
 */
request.use(async (ctx: Context, next: () => void) => {
  await next();

  const { res } = ctx;

  if (res?.errorCode === '402') {
    // 开发环境，且为子应用
    if (process.env.NODE_ENV === 'development' && ${isSubapp}) {
      console.warn('token expired, please check.');
    } else {
      console.warn('token expired, please check.');
      window.dispatchEvent(new Event('tokenExpire'));
    }
  } else if (res?.errorCode === '401') {
    // 开发环境，且为子应用
    if (process.env.NODE_ENV === 'development' && ${isSubapp}) {
      console.warn('no role, please check.');
    } else {
      console.warn('no role, please check.');
      window.dispatchEvent(new Event('norole'));
    }
  } else if (res?.success === false && ${showErrorWhenSuccessEqualFalse}) {
    message.error({
      content: res.errorMsg,
    });
  }
});`
    });
  });
  api.addRuntimePlugin(() => {
    return [(0, import_withTmpPath.withTmpPath)({ api, path: "runtime.ts" })];
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
